package org.codingq92.basic.io.nio;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 描述: 通过channel读取文件内容demo
 * <p>
 * ByteBuffer.allocate(1024); 堆内存，分配速度快，读写慢，受GC的影响
 * <p>
 * ByteBuffer.allocateDirect(1024); 直接内存，分配慢，读写快，不受GC的影响
 *
 * @author: CodingQ92
 * @date: 2025/7/1 22:54
 */
public class ByteBufferDemo {
    public static void main(String[] args) {
        String filePath = "/Users/smyxmac/Documents/workspace/ideaSpace/HandWritten/src/main/resources/小学汉字.txt";
        try (FileChannel fileChannel = new FileInputStream(filePath).getChannel()) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            while (true) {
                int read = fileChannel.read(byteBuffer);
                if (read == -1) {
                    break;
                }
                byteBuffer.flip();
                String s = new String(byteBuffer.array(), 0, byteBuffer.remaining());
                System.out.println(s);
                byteBuffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
